package com.hmall.item.listener;

import cn.hutool.json.JSONUtil;
import com.hmall.common.constant.ESConstants;
import com.hmall.common.constant.MQConstants;
import com.hmall.item.domain.po.ItemDoc;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
@Component
@RequiredArgsConstructor
@Slf4j
public class UpdateItemDocListener {

    private final RestHighLevelClient client;
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MQConstants.ITEM_UPDATE_QUEUE_NAME, durable = "true"),
            exchange = @Exchange(name = MQConstants.ITEM_EXCHANGE_DIRECT_NAME),
            key = MQConstants.ITEM_UPDATE_ROUTING_KEY
    ))
    public void updateStatus(ItemDoc itemDoc) {
        try {
            IndexRequest request = new IndexRequest(ESConstants.INDEX_NAME).id(String.valueOf(itemDoc.getId()));
            request.source(JSONUtil.toJsonStr(itemDoc), XContentType.JSON);
            client.index(request, RequestOptions.DEFAULT);
            log.info("修改商品状态成功, id:{}", itemDoc.getId());
        } catch (Exception e) {
            log.error("修改商品状态失败, id:{}, 异常信息：{}", itemDoc.getId(), e.getMessage());
        }

    }
}
